import "package:ct_pa_majordomo/config/roomIcons.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/home/api.dart";
import "package:ct_pa_majordomo/pages/home/sections/device.dart";
import "package:ct_pa_majordomo/pages/home/sections/overview.dart";
import "package:ct_pa_majordomo/pages/home/sections/todo.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/widgets/button/tap_container.dart";
import "package:flutter/material.dart";
import 'package:marquee/marquee.dart'; // 导入 Marquee 包

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  Map params = {};
  Map<String, dynamic> _electricityTrendParams = {
    "type": "month",
    "startDate": DateTools.formatYMD(DateTime.now().subtract(const Duration(days: 30)), format: "{y}-{m}-{d} {h}:{i}:{s}"),
    "endDate": DateTools.formatYMD(DateTime.now(), format: "{y}-{m}-{d} {h}:{i}:{s}"),
  };

  Future<void> _getStatistics() async {
    try {
      Map apartmentStatistics = await homeApi.apartmentStatistics();
      Map billStatistics = await homeApi.billStatistics();
      Map trendStatistics = await homeApi.trendStatistics();
      Map roomStatistics = await homeApi.roomStatistics();
      Map electricityStatistics = await homeApi.electricityStatistics();
      Map electricityTrend = await homeApi.electricityTrend(_electricityTrendParams);

      if (mounted) {
        setState(() {
          params = {
            ...billStatistics["data"] ?? {},
            ...trendStatistics["data"] ?? {},
            ...apartmentStatistics["data"] ?? {},
            ...roomStatistics["data"] ?? {},
            ...electricityStatistics["data"] ?? {},
            ...electricityTrend["data"] ?? {},
          };
        });
      }
    } catch (e) {
      print('Error fetching statistics: $e');
    }
  }

  Future<void> _getElectricityTrend([Map<String, dynamic>? newParams]) async {
    // 如果传入了新参数，则更新_electricityTrendParams
    if (newParams != null) {
      setState(() {
        _electricityTrendParams = {
          ..._electricityTrendParams,
          ...newParams,
        };
      });
    }
    
    try {
      Map electricityTrend = await homeApi.electricityTrend(_electricityTrendParams);
      
      if (mounted) {
        setState(() {
          params = {
            ...params,
            ...electricityTrend["data"] ?? {},
          };
        });
      }
    } catch (e) {
      print('Error fetching electricity trend: $e');
    }
  }
  
  // 添加刷新方法，供外部调用
  void refresh() {
    _getStatistics();
  }
  
  @override
  bool get wantKeepAlive => false; // 不保持状态，每次都刷新

  @override
  void initState() {
    super.initState();
    _getStatistics();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return RefreshIndicator(
      onRefresh: () async {
        await _getStatistics();
      },
      child: ListView(
        padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage) +
            MediaQuery.paddingOf(context),
        children: [
          // // 使用 Marquee 组件实现自动滚动
          // Container(
          //   height: 32,
          //   color: ThemeVars.colorWarning,
          //   child: Marquee(
          //     text: "这是一个通告栏，内容过长时会从右向左滚动，滚动的内容为一大串。",
          //     style: const TextStyle(fontSize: 12,),
          //     scrollAxis: Axis.horizontal,
          //     crossAxisAlignment: CrossAxisAlignment.center,

          //     blankSpace: 20.0,
          //     velocity: 50.0,
          //     pauseAfterRound: Duration(seconds: 1),
          //     startPadding: 10.0,
          //   ),
          // ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              IconButton(
                onPressed: () {
                  Navigator.pushNamed(context, Keys.NOTICE_LIST);
                },
                icon: const Icon(Icons.notifications, color: ThemeVars.colorPrimary,),
              ),
              
            ],
          ),
          const SizedBox(height: 15),
          Todo(params: params),
          const SizedBox(height: 15),
          Device(),
          const SizedBox(height: 15),
          Overview(params: params, changeInfo: _getElectricityTrend),
        ],
      ),
    );
  }
}